package com.weitu.risk.controller;

import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.risk.entity.Recognise;
import com.weitu.risk.service.RecogniseDetailService;
import com.weitu.risk.service.RecogniseService;
import com.weitu.risk.service.SeriousService;
import com.weitu.util.AjaxResult;
import com.weitu.util.IDGenerator;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.fireflow.engine.IProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * 重大风险评审controller
 * Created by fanyuting on 2017/5/11 0011.
 */
@Controller
@RequestMapping("risk/serious/")
public class SeriousController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH+"risk/serious/";
    @Autowired
    private SeriousService seriousService;
    @Autowired
    private RecogniseService recogniseService;
    @Autowired
    private RecogniseDetailService recogniseDetailService;
    @Autowired
    private FlowManagementService flowManagementService;//流程管理service
    private WorkflowReview workflowReview;
    /**
     * 跳转到列表页面
     * @return
     */
    @RequestMapping("list")
    public String toSeriousListPage(){
        return MODULE_BATH_PATH+"list";
    }

    /**
     * 查询分页列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("queryListByParam")
    public Object queryListByParam(HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();
        //获取前台参数
        putParametersIntoMap(map);
        Integer totalNum = this.seriousService.queryListCountByParam(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);
        List<Map<String,Object>> list =  this.seriousService.queryListByParam(map);
        return  pagination.flushDataGridData(list);
    }

    /**
     * 跳转到编辑页面
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("edit")
    public String toSeriousEditPage(Model model,HttpServletRequest request){
        String detailId = request.getParameter("detailId");//recogniseDetailId
        String seriousId = request.getParameter("seriousId");
        //查询重大风险评审信息
        Map<String,Object> serious = new HashMap<String,Object>();
        //判断是否有重大风险评审信息
        String recogniseDetailId = detailId;
        if(!"undefined".equals(seriousId)){
            serious = this.seriousService.queryInfoById(seriousId);
            recogniseDetailId = String.valueOf(serious.get("recogniseDetailId"));
        }
        //查询风险识别评价信息详情
        Map<String,Object> recogniseDetail = recogniseDetailService.queryRecogniseDetailById(recogniseDetailId);
        //查询风险识别评价基本信息
        String recogniseId = String.valueOf(recogniseDetail.get("recogniseId"));
        Recognise recognise = recogniseService.queryRecogniseById(recogniseId);

        model.addAttribute("recogniseDetailId",detailId);
        model.addAttribute("recognise",recognise);
        model.addAttribute("serious",serious);
        return MODULE_BATH_PATH+"edit";
    }
    /**
     * 跳转到编辑页面
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("detail")
    public String toSeriousDetailPage(Model model,HttpServletRequest request){
        String detailId = request.getParameter("detailId");//recogniseDetailId
        String seriousId = request.getParameter("seriousId");
        //查询重大风险评审信息
        Map<String,Object> serious = new HashMap<String,Object>();
        //判断是否有重大风险评审信息
        String recogniseDetailId = detailId;
        if(!"undefined".equals(seriousId)){
            serious = this.seriousService.queryInfoById(seriousId);
            recogniseDetailId = String.valueOf(serious.get("recogniseDetailId"));
        }
        //查询风险识别评价信息详情
        Map<String,Object> recogniseDetail = recogniseDetailService.queryRecogniseDetailById(recogniseDetailId);
        //查询风险识别评价基本信息
        String recogniseId = String.valueOf(recogniseDetail.get("recogniseId"));
        Recognise recognise = recogniseService.queryRecogniseById(recogniseId);

        model.addAttribute("recogniseDetailId",detailId);
        model.addAttribute("recognise",recognise);
        model.addAttribute("serious",serious);
        return MODULE_BATH_PATH+"detail";
    }

    /**
     * 保存重大风险评审信息
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/addSeriousInfo")
    @Transactional
    public AjaxResult addSeriousInfo(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map = new HashMap<String,Object>();
        boolean flag = true;
        String id = request.getParameter("id");
        if(id!=null&&!"".equals(id)){
            //判断是否已审批
            Map<String,Object> serious = this.seriousService.queryInfoById(id);
            String appState = String.valueOf(serious.get("appState"));
            if("1".equals(appState)){//已审批
                //复制数据
                String newId = this.seriousService.copySerious(id);
                //编辑复制的数据
                getEditBasicFieldMap(map);
                map.put("id",newId);
                flag = this.seriousService.editSerious(map);
            }else{
                getEditBasicFieldMap(map);
                flag = this.seriousService.editSerious(map);
            }

        }else{
            getAddBasicFieldMap(map);
            String copyId = IDGenerator.getId();
            map.put("copyId",copyId);
            map.put("copyVersion",0);
            //保存重大风险评审信息
            flag = this.seriousService.addSerious(map);
        }
        if(flag ){
            return success("重大风险评审信息保存成功！");
        }
        return fail("重大风险评审信息保存失败！");
    }



    /*======================审批=======================*/
    /**
     * 提交审批
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submitApplication",method = RequestMethod.POST)
    public AjaxResult submitApplication(HttpServletRequest request)throws Exception{
        User crrentUser=this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);

        String businessId=paramMap.get("id").toString();//seriousId
        String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
        //获取信息
        //Map<String,Object> serious = this.seriousService.queryInfoById(businessId);
        //Recognise recognise = this.recogniseService.queryRecogniseById(businessId);
        // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
        /**
         * 复制信息并获取新的id
         */
        businessId = this.seriousService.copySerious(businessId);
        //启动流程实例
        IProcessInstance processInstance=this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_RISK_SERIOUS,businessId,"业务描述信息",nextUserId);
        boolean appStateFlag = false;
        if (processInstance!=null){
            appStateFlag = this.seriousService.editAppState(businessId,"0");
        }
        if (appStateFlag){
            result.setMessage("提交成功！");
            result.setSuccess(true);
        }else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }


    /***
     * 跳转到信息审批页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toApplicationVerify")
    public ModelAndView toApplicationVerify(HttpServletRequest request) {
        User crrentUser=this.getSessionUser();
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取参数
        putParametersIntoMap(paramMap);
        String businessId=paramMap.get("businessId").toString();//获取业务id，以businessId命名
        //工作项id
        String workItemId=paramMap.get("workItemId").toString();
        //表单类型；0：只读表单；1：编辑表单
        int formType=paramMap.get("formType")!=null?Integer.parseInt(paramMap.get("formType").toString()):0;
        modelAndView.addObject("workItemId",workItemId);
        modelAndView.addObject("formType",formType);
        //获取意见信息
        WorkflowReview workflowReview=this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
        modelAndView.addObject("workflowReview",workflowReview);

        /**
         * 业务信息
         */
        //Recognise recognise = this.recogniseService.queryRecogniseById(businessId);
        Map<String,Object> serious = this.seriousService.queryInfoById(businessId);
        String recogniseDetailId = String.valueOf(serious.get("recogniseDetailId"));
        //查询风险识别评价信息详情
        Map<String,Object> recogniseDetail = recogniseDetailService.queryRecogniseDetailById(recogniseDetailId);
        //查询风险识别评价基本信息
        String recogniseId = String.valueOf(recogniseDetail.get("recogniseId"));
        Recognise recognise = recogniseService.queryRecogniseById(recogniseId);
        modelAndView.addObject("serious",serious);
        modelAndView.addObject("recogniseDetailId",recogniseDetailId);
        modelAndView.addObject("recognise",recognise);
        //步骤：第几步信息
        String step = request.getParameter("step");
        modelAndView.addObject("step",step);
        //modelAndView.addObject("accessoryList",accessoryList);
        //modelAndView.addObject("uploadUserId",crrentUser.getId());
        modelAndView.setViewName(MODULE_BATH_PATH + "verify");
        return modelAndView;
    }

    /**
     * 审批信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "verifyApplication")
    public AjaxResult verifyApplication(HttpServletRequest request)throws Exception{
        String businessId = request.getParameter("businessId");
        String workItemId=request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview=this.flowManagementService.getWorkflowReviewByRequest(request,"workflowReview",workItemId);
        //保存处理结果
        boolean boo=this.flowManagementService.saveWorkflowReview(workflowReview);
        //步骤：第几步信息
        String step = request.getParameter("step");
        //结束环节，继续流程向下执行
        if (boo){
            //更改业务中的审批状态
            String result = workflowReview.getResult();
            if("1".equals(result)){
                if("2".equals(step)){
                    this.seriousService.editAppState(businessId,"1");
                }
            }else{
                if("2".equals(step)){
                    this.seriousService.editAppState(businessId,"-1");
                }

            }

            this.flowManagementService.workItemComplete(workItemId);
        }
        // System.out.println(workflowReview.getComments());

        AjaxResult result = new AjaxResult();
        if (boo){
            result.setMessage("提交成功！");
            result.setSuccess(true);
        }else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }
}
